//
//  ViewController.m
//  iosnfc
//
//  Created by sujeking on 25/04/2021.
//

#import "ViewController.h"
#import "NFCManager.h"
@interface ViewController ()
@property (nonatomic, strong) NFCManager *nfcManager;


@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UITextView *readTextView;
@property (weak, nonatomic) IBOutlet UITextView *sendTextView;



@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self pageSetupUI];
    [self initNFCManager];
}


- (void)pageSetupUI {
    [self.view setBackgroundColor:[UIColor orangeColor]];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)initNFCManager {
    self.nfcManager = [NFCManager sharedInstance];
    
    NFCSupportsStatus rstatus = [NFCManager isSupportsNFCReading];
    NFCSupportsStatus wstatus = [NFCManager isSupportsNFCWrite];

    if (rstatus == NFCSupportStatusDeviceNo || wstatus == NFCSupportStatusDeviceNo) {
        self.statusLabel.text = @"硬件设备不支持";
        return;
    }

    if (rstatus == NFCSupportStatusnSystemNo && wstatus == NFCSupportStatusnSystemNo) {
        self.statusLabel.text = @"系统不支持NFC操作";
        return;
    }
    
    if (rstatus == NFCSupportStatusnSystemNo) {
        self.statusLabel.text = @"系统不支持读取NFC";
        return;
    }
    
    if (wstatus == NFCSupportStatusnSystemNo) {
        self.statusLabel.text = @"系统不支持写NFC";
        return;
    }
    
    self.statusLabel.text = @"NFC is OK";
    
    if (rstatus == NFCSupportStatusYes && wstatus == NFCSupportStatusYes) {
        __weak typeof(self) weakSelf = self;
        [self.nfcManager scanTagWithSuccessBlock:^(NFCNDEFMessage * message) {
            NSString *txt = @"";
            for (NFCNDEFPayload *record in message.records) {
                NSString *str = [[NSString alloc] initWithData:record.payload encoding:NSASCIIStringEncoding];
                txt = [txt stringByAppendingString:str];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.readTextView.text = txt;
            });
        } andErrorBlock:^(NSError * _Nonnull error) {
            
        }];
    }
}

// MARK: - Action

- (IBAction)readMsg:(id)sender {
    __weak typeof(self) weakSelf = self;
    [self.nfcManager scanTagWithSuccessBlock:^(NFCNDEFMessage * message) {
        NSString *txt = @"";
        for (NFCNDEFPayload *record in message.records) {
            NSString *str = [[NSString alloc] initWithData:record.payload encoding:NSASCIIStringEncoding];
            txt = [txt stringByAppendingString:str];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.readTextView.text = txt;
        });
    } andErrorBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (IBAction)handleSendAction:(id)sender {
    NFCNDEFMessage *message = [self createMessageWithTextRecord:self.sendTextView.text appendPackage:YES];
    [self.nfcManager writeMessage:message ToTagWithSuccessBlock:^{
        
    } andErrorBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (IBAction)handleSendDefaultAction:(id)sender {
    
}

- (IBAction)handleCleanAction:(id)sender {
    NFCNDEFMessage *message = [self createMessageWithTextRecord:@"" appendPackage:YES];
    [self.nfcManager writeMessage:message ToTagWithSuccessBlock:^{
        
    } andErrorBlock:^(NSError * _Nonnull error) {
        
    }];
}

// MARK: - Action

-(NFCNDEFMessage *)createMessageWithTextRecord: (NSString *)text appendPackage:(bool)appendPackage{
    NFCNDEFMessage * message;
    
    // Calculate and compute the payload headers and fields
    char typeBytes [] = {0x54};
    char idBytes [] = {0x00};
    char payloadHeaderBytes [] = {0x02, 0x65, 0x6E};
    
    NSString * payloadHeader = [[NSString alloc] initWithBytes:payloadHeaderBytes length:sizeof(payloadHeaderBytes) encoding:(NSStringEncoding)NSASCIIStringEncoding];
    
    text = [NSString stringWithFormat:@"%@%@", payloadHeader, text];
    
    // Initialize properties to create NFCNDEFPayload object
    NFCTypeNameFormat nfcTypeFormat = NFCTypeNameFormatNFCWellKnown;
    NSData * type = [[NSData alloc]initWithBytes:typeBytes length:sizeof(typeBytes)];
    NSData * identifier = [[NSData alloc]initWithBytes:idBytes length:sizeof(idBytes)];
    NSData * payloadData = [text dataUsingEncoding: NSASCIIStringEncoding];
    
    NFCNDEFPayload *payload = [[NFCNDEFPayload alloc] initWithFormat:nfcTypeFormat type:type identifier:identifier payload:payloadData];
    NSMutableArray<NFCNDEFPayload *> *records = [[NSMutableArray alloc] init];
    [records addObject:payload];
    
    if (appendPackage){
        // Initialize properties to create NFCNDEFPayload object
        NFCTypeNameFormat nfcTypeFormatPackage = NFCTypeNameFormatNFCExternal;
        NSData * typePackage = [@"ios.com:pkg" dataUsingEncoding: NSASCIIStringEncoding];
        NSData * payloadPackage = [@"cmo.nxp.ntagi2cdemo" dataUsingEncoding: NSASCIIStringEncoding];
        NSData * identifierPackage = [[NSData alloc] init];
        // Create External Record Payload Object
        NFCNDEFPayload * payloadPkg = [[NFCNDEFPayload alloc] initWithFormat:nfcTypeFormatPackage type:payloadPackage identifier:identifierPackage payload:payloadPackage];
        [records addObject:payloadPkg];
    }
    
    // Generate NFCNDEFMessage object
    message = [[NFCNDEFMessage alloc] initWithNDEFRecords:records];
    
    return message;
}


@end
